/**
 * Created by robot
 * DATE 2021/08/03
 * Describe
 */
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { routerConfig } from './type';
let routeFlag = false

export default class baseVueRouter {
  protected config: routerConfig
  constructor(config: routerConfig) {
    this.config = {
      token: null,
      constantRouter: [],
      whiteListRouter: [],
      noAuthPath: '',
      errorPath: '',
      loginRedirectRouter: '',
      dynamicRouters: [],
      callBackBreadCrumb: null,
      callBackLogin: null,
      callBackNoAuth: null,
      callBackError: null,
      callBackBeforeEach: null,
      callBackAfterEach: null
    }
    // 合并config配置
    for (const item in this.config) {
      // 只有传入的config有值时才会进行覆盖
      if (config[item]) {
        this.config[item] = config[item]
      }
    }
  }

  /**
   * 路由实例生成及初始化
   */
  initRouter() {
    const constantRouterMap: RouteRecordRaw[] = []
    if (this.config.constantRouter) {
      constantRouterMap.push(...this.config.constantRouter)
    }
    if (this.config.whiteListRouter) {
      constantRouterMap.push(...this.config.whiteListRouter)
    }
    const router = createRouter({
      history: createWebHistory(),
      routes: constantRouterMap
    })

    router.beforeEach(async (to, from, next) => {
      if (this.config.callBackBreadCrumb) {
        this.config.callBackBreadCrumb(to, from, next)
      }
      // 登录及白名单页面放行，多个子系统单独登录的退出，需要将当前的登录页面存放到session
      if (to.meta.isLogin || to.meta.isWhite) {
        to.meta.isLogin ? window.sessionStorage.setItem('LOGIN_URL', to.path) : ''
        // 自定义的登录处理函数
        if (this.config.callBackLogin) {
          this.config.callBackLogin(to, from, next)
        }
        next()
      } else {
        if (this.config.token && this.config.token()) {
          if (routeFlag) {
            next()
          } else {
            if (this.config.callBackBeforeEach) {
              await this.config.callBackBeforeEach(to, from, next)
              routeFlag = true
              next({ ...to, replace: true })
            }
          }
        } else {
          // 自定义无权限处理函数
          if (this.config.callBackNoAuth) {
            this.config.callBackNoAuth(to, from, next)
          }
          // 如果配置了无权限时跳转的路由，则进行跳转
          if (this.config.noAuthPath) {
            next(this.config.noAuthPath)
          }
        }
      }
    })

    router.afterEach((to, from) => {
      if (this.config.callBackAfterEach) {
        this.config.callBackAfterEach(to, from)
      }
    })

    // 出现错误则跳转到404页面from
    router.onError((e) => {
      // 跳转之前进行的错误处理，例如错误上报等等
      if (this.config.callBackError) {
        this.config.callBackError(e)
      }
      if (this.config.errorPath) {
        router.replace({
          path: this.config.errorPath
        })
      }
    })
    return router
  }
}
